package com.xl.tools;

import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xddf.usermodel.chart.LegendPosition;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws IOException {
        File oldpath = new File("D:\\tangzhichao\\pics.xlsx");
        Path path = Paths.get("D:/tangzhichao/test.xlsx");
        if(Files.exists(path)) {
            Files.delete(path);
        }
        Files.copy(Paths.get(oldpath.getAbsolutePath()),path);
        XSSFWorkbook XSSfWorkbook = new XSSFWorkbook(Files.newInputStream(path));
        File pngDir = new File("D:\\tangzhichao\\qrcodes");
        File[] listFile = pngDir.listFiles();
        int row = 0;
        int col = 0;
        for (int i = 0; i < listFile.length; i++) {
            File item = listFile[i];
            if (!item.getName().toLowerCase().endsWith(".png")) {
                continue;
            }
            if (i != 0 && i % 3 == 0) {
                row++;
                col = 0;
            }
            System.out.println("行：" + row);
            System.out.println("列：" + col);
            System.out.println("图片" + item.getAbsolutePath());
            //图片文件  我这儿使用的是本地文件
            byte[] bytes = Files.readAllBytes(Paths.get(item.getAbsolutePath()));
            int pictureIdx = XSSfWorkbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
            XSSFSheet sheet = XSSfWorkbook.getSheetAt(0);
//            XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();
//            XSSFClientAnchor anchor = new XSSFClientAnchor();
//            anchor.setCol1(col);
//            anchor.setRow1(row);
//            anchor.setCol2(col  );
//            anchor.setRow2(row );
//            CTPoint2D ctPoint2D = anchor.getPosition();
//            ctPoint2D.setX(50);
//            ctPoint2D.setY(50);
////            anchor.setDx1(50);
////            anchor.setDy1(50);
////            anchor.setDx2(10);
////            anchor.setDy2(10);
//            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
//            XSSFPicture pic = drawingPatriarch.createPicture(anchor, pictureIdx);
//            pic.resize();
            col++;

        }
        try (FileOutputStream out = new FileOutputStream(path.toFile())) {
            //输出
            XSSfWorkbook.write(out);
        }
    }
}
